<?php 
/**
 * simple_confirm.php
 *
 * Order confirmation simple way, no payment_method, shipping method needed
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestSimpleCheckout extends RestController {
    /*
		Confirm order
	*/
	public function confirmOrder() {
        $this->checkPlugin();
        $order_data = array();
        $json = array('success' => true);

        if (!$this->cart->hasShipping()) {
            unset($this->session->data['shipping_address']);
            unset($this->session->data['shipping_method']);
            unset($this->session->data['shipping_methods']);
        }
        // Validate cart has products and has stock.
        if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $json["error"]['warning']		= "购物车内产品不足或购物车为空";
            $json["success"]	= false;
        }

        // Validate minimum quantity requirements.
        $products = $this->cart->getProducts();

        if(isset($this->session->data['sample_checkout'])&&$this->session->data['sample_checkout']==1){
        } else {
            foreach ($products as $product) {
                $product_total = 0;
                foreach ($products as $product_2) {
                    if ($product_2['product_id'] == $product['product_id']) {
                        $product_total += $product_2['quantity'];
                    }
                }

                if ($product['minimum'] > $product_total) {
                    $json["error"]['warning'] = $product['name'] . " 购买的数量小于最小起批量";
                    $json["success"] = false;
                    $this->response->setOutput(json_encode($json));
                    return;
                    break;
                }
            }
        }

        $this->load->model('account/customer');
        $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
        $order_data['email'] = $customer_info['email'];

        //用户是否有关联物流营销中心检查
        $logcenter_id = $this->customer->getLogcenterId();
        if(!$logcenter_id || $logcenter_id == 0) {
            $json['success'] = false;
            $json["error"]['warning'] = '用户还未关联物流营销中心，不能下单';
            $this->response->setOutput(json_encode($json));
            return;
        }
         // var_dump($this->customer);
        $this->load->model('account/address');
        
        $is_buy =  $json['is_buy'] = $this->model_account_address->getIsBuy(0);
        $buylog_name = $this->customer->getLogName(); 
        $buylog_user = $this->customer->getLogUser(); 
        $buylog_telephone = $this->customer->getLogTelephone(); 
        if( $is_buy == 0) {
            $json['success'] = false;
            $json["error"]['warning']       = '对不起，您暂时不能下单，请联系您所在'.$buylog_name.'的客户经理：'.$buylog_user.', 电话：'.$buylog_telephone;
            $this->response->setOutput(json_encode($json));
            return;
        }

        //购物车金额限制检查
        $min_cart_amount = 500;
        if($this->cart->getSubTotal() < $min_cart_amount) {
            $json['success'] = false;
            $json["error"]['warning'] = '不满最小下单金额￥' . $min_cart_amount . '！';
            $this->response->setOutput(json_encode($json));
            return;
        }



        //首次拿样订单判断
        if(isset($this->session->data['sample_checkout']) && $this->session->data['sample_checkout']==1) {
            if(isset($customer_info['sample_bill_amount'])&&$customer_info['sample_bill_amount']!=0) {
                $json['success'] = false;
                $json["error"]['warning'] = '此用户已免费拿样过';
                $this->response->setOutput(json_encode($json));
                return;
            }
            $err_msg = $this->verifyCartForSample();
            if($err_msg != '') {
                $json['success'] = false;
                $json["error"]['warning'] = $err_msg;
                $this->response->setOutput(json_encode($json));
                return;
            }
        }

        if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
            $requestjson = file_get_contents('php://input');
            $requestjson = json_decode($requestjson, true);
            $post  = $requestjson;
            $post_address_id = $post['address_id'];
            if(isset($post['address_id'])) {
                $post_address_id=$post['address_id'];
                $this->load->model('account/address');
                $address_info = $this->model_account_address->getAddress($post_address_id);
                if(!$address_info){
                    $json["success"] = false;
                    $json['error']['warning'] = '请选择收货地址！';
                    $this->response->setOutput(json_encode($json));
                }else{
                    $order_data['shipping_telephone'] = $address_info['shipping_telephone'];
                }
            }else{
                $json["success"] = false;
                $json['error']['warning'] = '请选择收货地址！';
                $this->response->setOutput(json_encode($json));
            }


            $payment_method_error = '';
            if(isset($post['payment_method']) && isset($post['payment_code'])) {
                if (!isset($this->session->data['payment_methods'])) {
                    $payment_method_error = '请先进入结账页面';
                } else {
                    if(!array_key_exists($post['payment_code'], $this->session->data['payment_methods'])) {
                        $payment_method_error = '未找到支付方式';
                    }
                }
            } else {
                $payment_method_error = '请选择支付方式！';
            }

            //磁金融权限检查
            $is_magfin = $this->customer->getIsMagfin();
            $log_name = $this->customer->getLogName(); 
            $log_user = $this->customer->getLogUser(); 
            $log_telephone = $this->customer->getLogTelephone(); 
            if($post['payment_code'] == 'magfin' && $is_magfin == 1) {
                $json['success'] = false;
                $json["error"]['warning']		= '对不起，您暂时无法使用该支付方式，请联系您所在'.$log_name.'的客户经理：'.$log_user.', 电话：'.$log_telephone;
                $this->response->setOutput(json_encode($json));
                return;
            }

            //检查礼品
            if($post['payment_code'] == 'cod'){
                foreach ($this->cart->getProducts() as $product) {
                    if($product['product_id'] == '2999') {
                        $id = $product['cart_id'];
                        if(!empty($id)) {
                            $this->cart->remove($id);
                            unset($this->session->data['vouchers'][$id]);
                        }
                    }
                    if($product['product_id'] == '3000') {
                        $id = $product['cart_id'];
                        if(!empty($id)) {
                            $this->cart->remove($id);
                            unset($this->session->data['vouchers'][$id]);
                        }
                    }
                    if($product['product_id'] == '3001') {
                        $id = $product['cart_id'];
                        if(!empty($id)){
                            $this->cart->remove($id);
                            unset($this->session->data['vouchers'][$id]);
                        }
                    }
                    //增加更多代码.....
                }
            }

            if($payment_method_error != '') {
                $json["success"] = false;
                $json['error']['warning'] = $payment_method_error;
                $this->response->setOutput(json_encode($json));
            }
        }

        if ($json["success"]) {
            $order_data['totals'] = array();
            $total = 0;
            $taxes = $this->cart->getTaxes();
            $this->load->model('extension/extension');
            $sort_order = array();
            $results = $this->model_extension_extension->getExtensions('total');
            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }
            array_multisort($sort_order, SORT_ASC, $results);
            // var_dump($results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('total/' . $result['code']);
                    // if($result['code'] != 'favour')
                    //     $this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
                    // else
                    //     $this->model_total_favour->getTotal($order_data['totals'], $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);

                    if($result['code'] != 'discount'&&$result['code'] != 'favour'){
                        $this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
                    }
                    else{
                        // echo 11;
                        // $this->model_total_favour->getTotal($order_data['totals'], $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);
                        if ($result['code'] == 'discount') {
                            if ($post['payment_code']=='magfin') {
                            // echo 1;
                                $flag = true;
                            }else{
                                // echo 2;
                                $flag = false;
                            }
                            $this->model_total_discount->getTotal($order_data['totals'], $total, $taxes,$flag );
                        }elseif($result['code'] == 'favour'){
                             $this->model_total_favour->getTotal($order_data['totals'], $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);
                        }
                        
                    }
                }
            }

            $sort_order = array();
            foreach ($order_data['totals'] as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }
            // var_dump($order_data['totals']);

            // array_multisort($sort_order, SORT_ASC, $order_data['totals']);
            // var_dump($order_data['totals']);

            $this->load->language('checkout/checkout');
            $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
            $order_data['store_id'] = $this->config->get('config_store_id');
            $order_data['store_name'] = $this->config->get('config_name');

            if ($order_data['store_id']) {
                $order_data['store_url'] = $this->config->get('config_url');
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }
            $payment_address = array();
            if ($this->customer->isLogged()) {
                $this->load->model('account/customer');
                $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
                $order_data['customer_id'] = $this->customer->getId();
                $order_data['customer_group_id'] = $customer_info['customer_group_id'];
                $order_data['fullname'] = $customer_info['fullname'];
                $order_data['telephone'] = $customer_info['telephone'];
                $order_data['fax'] = $customer_info['fax'];

                if(strpos(VERSION, '2.1.') === false){
                    $order_data['custom_field'] = unserialize($customer_info['custom_field']);
                } else {
                    $order_data['custom_field'] = json_decode($customer_info['custom_field'], true);
                }

                $this->load->model('account/address');
                if($post_address_id) {
                    $this->session->data['payment_address']=$address_info;
                    $payment_address=$address_info;
                } elseif(isset($this->session->data['payment_address']['address_id'])) {
                    $payment_address = $this->model_account_address->getAddress($this->session->data['payment_address']['address_id']);
                } else {
                    $payment_address = $this->model_account_address->getAddress($this->customer->getAddressId());
                } 
            }

            if($json["success"]) {
                $order_data['payment_fullname'] = $payment_address['fullname'];
                $order_data['payment_company'] = $payment_address['company'];
                $order_data['payment_address'] = $payment_address['address'];
                $order_data['payment_city'] = $payment_address['city'];
                $order_data['payment_city_id'] = $payment_address['city_id'];
                $order_data['payment_postcode'] = $payment_address['postcode'];
                $order_data['payment_zone'] = $payment_address['zone'];
                $order_data['payment_zone_id'] = $payment_address['zone_id'];
                $order_data['payment_country'] = $payment_address['country'];
                $order_data['payment_country_id'] = $payment_address['country_id'];
                $order_data['payment_address_format'] = $payment_address['address_format'];
                $order_data['payment_custom_field'] = $payment_address['custom_field'];
                $order_data['payment_method'] = $post['payment_method'];
                $order_data['payment_code'] = $post['payment_code'];
                $this->session->data['payment_method'] = $this->session->data['payment_methods'][$post['payment_code']];

                if ($this->cart->hasShipping()) {
                    $shipping_address = array();
                    if ($this->customer->isLogged()) {
                        $shipping_address = $address_info;
                        unset($this->session->data["shipping_address"]);
                        $this->session->data['shipping_address']=$address_info;
                        $order_data['shipping_fullname'] = $shipping_address['fullname'];
                        $order_data['shipping_company'] = $shipping_address['company'];
                        $order_data['shipping_address'] = $shipping_address['address'];
                        $order_data['shipping_city'] = $shipping_address['city'];
                        $order_data['shipping_city_id'] = $shipping_address['city_id'];
                        $order_data['shipping_postcode'] = $shipping_address['postcode'];
                        $order_data['shipping_zone'] = $shipping_address['zone'];
                        $order_data['shipping_zone_id'] = $shipping_address['zone_id'];
                        $order_data['shipping_country'] = $shipping_address['country'];
                        $order_data['shipping_country_id'] = $shipping_address['country_id'];
                        $order_data['shipping_address_format'] = $shipping_address['address_format'];
                        $order_data['shipping_custom_field'] = $shipping_address['custom_field'];
                        $default_shipping_method_info=array(
                            "title" => "免运费",
                            "quote" => array( 
                                "free" => array(
                                    "code" => "free.free",
                                    "title" => "免运费",
                                    "cost" => "0",
                                    "tax_class_id" => "0",
                                    "text" => "￥0.00"
                                )
                            ),
                            "sort_order" => "",
                            "error" => ""
                        );
                        $order_data['shipping_method'] = $default_shipping_method_info['title'];
                        $order_data['shipping_code'] = $default_shipping_method_info['quote']['free']['code'];
                        $this->session->data['shipping_method']= $default_shipping_method_info;
                    }
                }else{//修改
                    $order_data['shipping_fullname'] = '';
                    $order_data['shipping_company'] = '';
                    $order_data['shipping_address_1'] = '';
                    $order_data['shipping_address_2'] = '';
                    $order_data['shipping_city'] = '';
                    $order_data['shipping_city_id'] = '';
                    $order_data['shipping_postcode'] = '';
                    $order_data['shipping_zone'] = '';
                    $order_data['shipping_zone_id'] = '';
                    $order_data['shipping_country'] = '';
                    $order_data['shipping_country_id'] = '';
                    $order_data['shipping_address_format'] = '';
                    $order_data['shipping_custom_field'] = array();
                    $order_data['shipping_method'] = '';
                    $order_data['shipping_code'] = '';
                }
                $order_data['products'] = array();

				$spreadratio = $total/$this->cart->getSubTotal();

				foreach ($this->cart->getProducts() as $product) {
					$option_data = array();

					foreach ($product['option'] as $option) {
						$option_data[] = array(
							'product_option_id'       => $option['product_option_id'],
							'product_option_value_id' => $option['product_option_value_id'],
							'option_id'               => $option['option_id'],
							'option_value_id'         => $option['option_value_id'],
							'name'                    => $option['name'],
							'value'                   => $option['value'],
							'type'                    => $option['type']
						);
					}

					$order_data['products'][] = array(
                        'product_id' => $product['product_id'],
						'vendor_id' => $product['vendor_id'],
						'name'       => $product['name'],
                        'model'      => $product['model'],
						'product_type'      => $product['product_type'],
						'option'     => $option_data,
						'download'   => $product['download'],
						'quantity'   => $product['quantity'],
						'subtract'   => $product['subtract'],
						'price'      => $product['price'],
						'pay_price'  => round($product['price']*$spreadratio,2),
						'total'      => $product['total'],
						'pay_total'  => round($product['total']*$spreadratio,2),
						'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
						'reward'     => $product['reward']
					);
				}

				// Gift Voucher
				$order_data['vouchers'] = array();

				if (!empty($this->session->data['vouchers'])) {
					foreach ($this->session->data['vouchers'] as $voucher) {
						$order_data['vouchers'][] = array(
							'description'      => $voucher['description'],
							'code'             => substr(md5(mt_rand()), 0, 10),
							'to_name'          => $voucher['to_name'],
							'to_email'         => $voucher['to_email'],
							'from_name'        => $voucher['from_name'],
							'from_email'       => $voucher['from_email'],
							'voucher_theme_id' => $voucher['voucher_theme_id'],
							'message'          => $voucher['message'],
							'amount'           => $voucher['amount']
						);
					}
				}

				$order_data['comment'] = isset($this->session->data['comment']) ? $this->session->data['comment'] : "";
				$order_data['total'] = $total;
				$order_data['ori_total'] = $total;
            

			
				if (isset($this->request->cookie['tracking'])) {
					$order_data['tracking'] = $this->request->cookie['tracking'];

					$subtotal = $this->cart->getSubTotal();

					// Affiliate
					$this->load->model('affiliate/affiliate');

					$affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);

					if ($affiliate_info) {
						$order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
						$order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
					} else {
						$order_data['affiliate_id'] = 0;
						$order_data['commission'] = 0;
					}

					// Marketing
					$this->load->model('checkout/marketing');

					$marketing_info = $this->model_checkout_marketing->getMarketingByCode($this->request->cookie['tracking']);

					if ($marketing_info) {
						$order_data['marketing_id'] = $marketing_info['marketing_id'];
					} else {
						$order_data['marketing_id'] = 0;
					}
				} else {
					$order_data['affiliate_id'] = 0;
					$order_data['commission'] = 0;
					$order_data['marketing_id'] = 0;
					$order_data['tracking'] = '';
				}

				$order_data['language_id'] = $this->config->get('config_language_id');
				$order_data['currency_id'] = $this->currency->getId();
				$order_data['currency_code'] = $this->currency->getCode();
				$order_data['currency_value'] = $this->currency->getValue($this->currency->getCode());
				$order_data['ip'] = $this->request->server['REMOTE_ADDR'];

				if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
					$order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
				} elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
					$order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
				} else {
					$order_data['forwarded_ip'] = '';
				}

				if (isset($this->request->server['HTTP_USER_AGENT'])) {
					$order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
				} else {
					$order_data['user_agent'] = '';
				}

				if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
					$order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
				} else {
					$order_data['accept_language'] = '';
				}

				if(isset($this->session->data['sample_checkout']) && $this->session->data['sample_checkout']==1) {
					$order_data['is_sample_order'] = '1';
				}

				$order_data['logcenter_id'] = $this->customer->getLogcenterId();

				$this->load->model('checkout/order');

				$this->session->data['order_id'] = $this->model_checkout_order->addOrder($order_data,$spreadratio);
				//添加应收
				$moneyorder = $this->model_checkout_order->getMoneyOrder($this->session->data['order_id']);
				if ($moneyorder) {
					$this->model_checkout_order->addMoneyOrder($moneyorder);
				}
 				

			
			  $data['products'] = array();

				foreach ($this->cart->getProducts() as $product) {
					$option_data = array();

					foreach ($product['option'] as $option) {
						if ($option['type'] != 'file') {
							$value = $option['value'];
						} else {
							$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

							if ($upload_info) {
								$value = $upload_info['name'];
							} else {
								$value = '';
							}
						}

						$option_data[] = array(
							'name'  => $option['name'],
							'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
						);
					}

					$recurring = '';

					if ($product['recurring']) {
						$frequencies = array(
							'day'        => $this->language->get('text_day'),
							'week'       => $this->language->get('text_week'),
							'semi_month' => $this->language->get('text_semi_month'),
							'month'      => $this->language->get('text_month'),
							'year'       => $this->language->get('text_year'),
						);

						if ($product['recurring_trial']) {
							$recurring = sprintf($this->language->get('text_trial_description'), $this->currency->format($this->tax->calculate($product['recurring']['trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['trial_cycle'], $frequencies[$product['recurring']['trial_frequency']], $product['recurring']['trial_duration']) . ' ';
						}

						if ($product['recurring_duration']) {
							$recurring .= sprintf($this->language->get('text_payment_description'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
						} else {
							$recurring .= sprintf($this->language->get('text_payment_until_canceled_description'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
						}
					}

					$data['products'][] = array(
						'key'        => isset($product['cart_id']) ? $product['cart_id'] : (isset($product['key']) ? $product['key'] :  ""),
						'product_id' => $product['product_id'],
						'name'       => $product['name'],
						'model'      => $product['model'],
						'option'     => $option_data,
						'recurring'  => $recurring,
						'quantity'   => $product['quantity'],
						'subtract'   => $product['subtract'],
						'price'      => $this->currency->format($this->tax->calculate(round($product['price']*$spreadratio,2), $product['tax_class_id'], $this->config->get('config_tax'))),
						'total'      => $this->currency->format($this->tax->calculate(round($product['price']*$spreadratio,2), $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']),
						'session'=>$this->session,
                        'href'       => ""//$this->url->link('product/product', 'product_id=' . $product['product_id']),
					);
				}

				// Gift Voucher
				$data['vouchers'] = array();

				if (!empty($this->session->data['vouchers'])) {
					foreach ($this->session->data['vouchers'] as $voucher) {
						$data['vouchers'][] = array(
							'description' => $voucher['description'],
							'amount'      => $this->currency->format($voucher['amount'])
						);
					}
				}

				$data['totals'] = array();

				foreach ($order_data['totals'] as $total) {
					$data['totals'][] = array(
						'title' => $total['title'],
						'text'  => $this->currency->format($total['value']),
					);
				}

                $data['payment'] = '';

			    // if(isset($this->session->data['payment_method']['code'])){
       //              $paymentCode = $this->session->data['payment_method']['code'];
       //              $noRedirect = array('cod', 'bank_transfer', 'cheque', 'free_checkout');

       //              if(!in_array($paymentCode, $noRedirect)){
       //                  $data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);

       //                  $data['column_name'] = $this->language->get('column_name');
       //                  $data['column_model'] = $this->language->get('column_model');
       //                  $data['column_quantity'] = $this->language->get('column_quantity');
       //                  $data['column_price'] = $this->language->get('column_price');
       //                  $data['column_total'] = $this->language->get('column_total');

       //                  $this->pay($data);
       //              }
			    // }

			    if(isset($this->session->data['payment_method']['code'])){
              $paymentCode = $this->session->data['payment_method']['code'];
              $noRedirect = array('cod', 'bank_transfer', 'cheque', 'free_checkout');

			  /*余额付款*/
			  if($paymentCode == "balance") {
               $this->payBalance($this->customer->getId(),$order_data['total']);
              }
              if($paymentCode == "alipay_direct") {
              	$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
				$this->saveOrderToDatabase();
              	$this->gateway_pay($data);
              }
              if($paymentCode == "kuaiqianb2b") {
              	$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
              	$this->gateway_pay($data);
              }
              $data['is_cod'] = false;
			  $data['pay_code'] = $paymentCode;
              if($paymentCode == "cod") {
               $this->saveOrderToDatabase();
              	$data['is_cod'] = true;
              }
              if($paymentCode == "kuaiqianmobile") {
              	$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
				$this->saveOrderToDatabase();
              	$this->gateway_pay($data);
              }
			  if($paymentCode == "wx_yijipay") {
              	$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
				$this->saveOrderToDatabase();
				$data['redirect'] = $data['payment'];
              }
			  if($paymentCode == "kj_yijipay") {
              	$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
				$this->saveOrderToDatabase();
				$data['redirect'] = $data['payment'];
              }
			  /*磁金融*/
			  if($paymentCode == "magfin") {
               $this->saveOrderToDatabase();
              }
			    }
			    
			    $json["data"] = $data;
			}
		}		
		if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
				echo '</pre>';
		} else {

			$this->response->setOutput(json_encode($json));
		}

  }


	/*Save order to Db*/
	public function saveOrderToDatabase() {
		
		$this->checkPlugin();
		
		$json = array('success' => true);
	

		$this->load->model('checkout/order');
		$comment = "";	
		if(isset($this->session->data['comment'])){
			$comment = $this->session->data['comment'];		
		}
		$data['is_pay'] = 0;
		$map['order_id'] = $this->session->data['order_id'];
		M('order')->where($map)->data($data)->save();

		if(isset($this->session->data['order_id'])){
			if($this->session->data['payment_method']['code'] == 'cod' || $this->session->data['payment_method']['code'] == 'magfin'){
				$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->model_checkout_order->findOrderStatus('待审核'), $comment);
			}else{
				$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->model_checkout_order->findOrderStatus('待付款'), $comment);
			}

			if (isset($this->session->data['order_id'])) {
                		$json['order_id'] = $this->session->data['order_id'];
				$this->cart->clear();

							// Add to activity log
			$this->load->model('account/activity');

			if ($this->customer->isLogged()) {
				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $this->customer->getFullname(),
					'order_id'    => $this->session->data['order_id']
				);

				$this->model_account_activity->addActivity('order_account', $activity_data);
			} else {
				$activity_data = array(
					'name'     => $this->session->data['guest']['fullname'] ,
					'order_id' => $this->session->data['order_id']
				);

				$this->model_account_activity->addActivity('order_guest', $activity_data);
			}

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
			unset($this->session->data['guest']);

            if(isset($this->session->data['comment'])){
				unset($this->session->data['comment']);			
			}			
			unset($this->session->data['order_id']);
			unset($this->session->data['coupon']);
			unset($this->session->data['reward']);
			unset($this->session->data['voucher']);
			unset($this->session->data['vouchers']);
			unset($this->session->data['totals']);
			unset($this->session->data['sample_checkout']);

			}	
		}else {
			$json["success"] = false;
			$json["error"]['warning']= "没有订单";
		}
		if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
				echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}

	}
	
	/*
	* ORDER CONFIRMATION AND SAVE FUNCTIONS
	*/	
	public function checkout() {
		$this->checkPlugin();
		if($this->customer->getNeedReview()){
			$json['success'] = false;
			$json['error']['warning'] = "用户未审核，不能下单";
			$this->response->setOutput(json_encode($json));
		} else {
			if ( $_SERVER['REQUEST_METHOD'] === 'PUT' ){
				$this->saveOrderToDatabase();
			}else if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
				$this->confirmOrder();
			}else if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
	      $this->getCheckout();
	    	}
		}
		
  }

  private function gateway_pay($data) {
  	echo $data['payment'];
  	die();
  }

  /*Start payment*/
  private function pay($data) {

      $response = '<html lang="en">'.
          '<head>'.
          '<meta charset="utf-8">'.
          '<meta http-equiv="X-UA-Compatible" content="IE=edge">'.
          '<meta name="viewport" content="width=device-width, initial-scale=1">'.
          '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">'.
          '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>'.
          '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>'.
          '</head>'.
          '<body>'.
          $this->load->view('default/template/checkout/confirm.tpl', $data).
          '</body>'.
          '</html>';
      echo($response);
      die;
  }

  //获取结账详细信息
  public function getCheckout() {

  		$post = array();
  		
  		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){

	  		$requestjson = file_get_contents('php://input');
			
			$requestjson = json_decode($requestjson, true);

			$post		 = $requestjson;

		}

        $json = array('success' => true);
        $this->language->load('checkout/cart');
        if (!isset($this->session->data['vouchers'])) {
            $this->session->data['vouchers'] = array();
        }
        if ($this->cart->hasProducts() || !empty($this->session->data['vouchers'])) {
            $points = $this->customer->getRewardPoints();
            $points_total = 0;
            foreach ($this->cart->getProducts() as $product) {
                if ($product['points']) {
                    $points_total += $product['points'];
                }
            }
            if (isset($this->error['warning'])) {
                $data['error_warning'] = $this->error['warning'];
            } elseif (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
                $data['error_warning'] = $this->language->get('error_stock');
            } else {
                $data['error_warning'] = '';
            }

            if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
                $data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
            } else {
                $data['attention'] = '';
            }
            if ($this->config->get('config_cart_weight')) {
                $data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
            } else {
                $data['weight'] = '';
            }
            $this->load->model('tool/image');
	        	$this->load->model('tool/upload');
            $data['products'] = array();
            $products = $this->cart->getProducts();
            foreach ($products as $product) {
                $product_total = 0;
                foreach ($products as $product_2) {
                    if ($product_2['product_id'] == $product['product_id']) {
                        $product_total += $product_2['quantity'];
                    }
                }
                if ($product['minimum'] > $product_total) {
                    $data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
                }
                if ($product['image']) {
                    $image = $this->model_tool_image->resize($product['image'], $this->config->get('config_rest_api_image_width'), $this->config->get('config_rest_api_image_height'));
                } else {
                    $image = '';
                }
                $option_data = array();
		foreach ($product['option'] as $option) {
			if ($option['type'] != 'file') {
				$value = $option['value'];
			} else {
				$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

				if ($upload_info) {
					$value = $upload_info['name'];
				} else {
					$value = '';
				}
			}

			$option_data[] = array(
				'name'  => $option['name'],
				'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
			);
		}

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')));
                } else {
                    $price = false;
                }

                // Display prices
                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $total = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']);
                } else {
                    $total = false;
                }

                $data['products'][] = array(
                    'key'      => isset($product['cart_id']) ? $product['cart_id'] : (isset($product['key']) ? $product['key'] :  ""),
                    'thumb'    => $image,
                    'name'     => $product['name'],
                    'model'    => $product['model'],
                    'option'   => $option_data,
                    'quantity' => $product['quantity'],
                    'stock'    => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
                    'reward'   => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
                    'price'    => $price,
                    'total'    => $total
                );
            }

            // Gift Voucher
            $data['vouchers'] = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $key => $voucher) {
                    $data['vouchers'][] = array(
                        'key'         => $key,
                        'description' => $voucher['description'],
                        'amount'      => $this->currency->format($voucher['amount']),
                        'remove'      => $this->url->link('checkout/cart', 'remove=' . $key)
                    );
                }
            }

    		$data['coupon_status'] = $this->config->get('coupon_status');

		if (isset($data['coupon'])) {
			$data['coupon'] = $data['coupon'];			
		} elseif (isset($this->session->data['coupon'])) {
			$data['coupon'] = $this->session->data['coupon'];
		} else {
			$data['coupon'] = '';
		}

		$data['voucher_status'] = $this->config->get('voucher_status');

		if (isset($data['voucher'])) {
			$data['voucher'] = $data['voucher'];				
		} elseif (isset($this->session->data['voucher'])) {
			$data['voucher'] = $this->session->data['voucher'];
		} else {
			$data['voucher'] = '';
		}

		$data['reward_status'] = ($points && $points_total && $this->config->get('reward_status'));

		if (isset($data['reward'])) {
			$data['reward'] = $data['reward'];				
		} elseif (isset($this->session->data['reward'])) {
			$data['reward'] = $this->session->data['reward'];
		} else {
			$data['reward'] = '';
		}

		// Totals
		$this->load->model('extension/extension');

		$total_data = array();
		$total = 0;
		$taxes = $this->cart->getTaxes();

		// Display prices
		if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
			$sort_order = array();

			$results = $this->model_extension_extension->getExtensions('total');

			foreach ($results as $key => $value) {
				$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
			}

			array_multisort($sort_order, SORT_ASC, $results);

			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
					$this->load->model('total/' . $result['code']);
                    // var_dump($result['code']);

					if($result['code'] != 'discount'&&$result['code'] != 'favour'){
						$this->{'model_total_' . $result['code']}->getTotal($total_data, $total, $taxes);
                    }
					else{
                        // echo 11;
                        // $this->model_total_favour->getTotal($total_data, $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);
                        if ($result['code'] == 'discount') {
                            if ($post['payment_code']=='magfin') {
                            // echo 1;
                                $flag = true;
                            }else{
                                // echo 2;
                                $flag = false;
                            }
                            $this->model_total_discount->getTotal($total_data, $total, $taxes,$flag );
                        }else{
                            $this->model_total_favour->getTotal($total_data, $total, $taxes, $post['payment_code']=='cod' || $post['payment_code']=='magfin'?true:false);
                        }
                        
                    }
                        
				}
			}

			$sort_order = array();

			foreach ($total_data as $key => $value) {
				$sort_order[$key] = $value['sort_order'];
			}

			array_multisort($sort_order, SORT_ASC, $total_data);
		}

		$data['totals'] = array();

		foreach ($total_data as $total) {
			$data['totals'][] = array(
				'title' => $total['title'],
				'text'  => $this->currency->format($total['value']),
				'price' => $total['value']
			);
		}
            $json["cart"] = $data;
        } else {
            $json['success']    = false;
            $json['error']['warning']		= '购物车是空的';
        }

     //添加用户常用地址
     $this->load->model('account/address');
    $data = array();
    $data['addresses'] = $this->model_account_address->getAddresses(0);
   
    // var_dump($data['is_buy']);
    // Custom Fields
    $this->load->model('account/custom_field');
    $data['custom_fields'] = $this->model_account_custom_field->getCustomFields($this->config->get('config_customer_group_id'));

    if(count($data['addresses']) > 0){
        $json["ship_address"] = $data;
        if(isset($this->session->data['payment_address']['address_id'])) {
        	$json['ship_address']["selected_address"] = $this->session->data['payment_address']['address_id'];	
        } else {
        	$json['ship_address']["selected_address"] = $this->model_account_address->getDefaultAddressId();
        }
        
    }else {
        $json['ship_address']["error"]["warning"] = "还没有地址";
    }

    $data = array();
		$this->language->load('checkout/checkout');
		$this->load->model('account/address');
		if (!isset($this->session->data['payment_address'])) {
			$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->model_account_address->getDefaultAddressId());
		}
		if (isset($this->session->data['payment_address'])) {
			// Selected payment methods should be from cart sub total not total!
			$total = $this->cart->getSubTotal();
			$this->load->model('extension/extension');
			$results = $this->model_extension_extension->getExtensions('payment');
			$recurring = $this->cart->hasRecurringProducts();
			foreach ($results as $result) {
				if ($this->config->get($result['code'] . '_status')) {
                    /*
                     * 禁止金华（28）、台州（25）、<!--嘉兴（27）-->物流中心的客户使用货到付款（cod）支付方式
                     * @author sonicsjh
                     */
                    //if (('cod' == $result['code']) && (28 == $this->customer->getLogcenterId() || 25 == $this->customer->getLogcenterId() || 27 == $this->customer->getLogcenterId())) {
                    if (('cod' == $result['code']) && (28 == $this->customer->getLogcenterId() || 25 == $this->customer->getLogcenterId())) {

						//首单放行
						$check = $this->checkFirst($this->customer->getId());
						if($check != 0){
							continue;
						}

                    }
                    $this->load->model('payment/' . $result['code']);
					$method = $this->{'model_payment_' . $result['code']}->getMethod($this->session->data['payment_address'], $total);
					if ($method) {
						if ($recurring) {
							if (method_exists($this->{'model_payment_' . $result['code']}, 'recurringPayments') && $this->{'model_payment_' . $result['code']}->recurringPayments()) {
								$method_data[$result['code']] = $method;
							}
						} else {
							$method_data[$result['code']] = $method;
						}
					}
				}
			}
			$sort_order = array();
			foreach ($method_data as $value) {
				$sort_order[] = $value['sort_order'];
			}		

			array_multisort($sort_order,SORT_ASC,$method_data);


			$this->session->data['payment_methods'] = $method_data;		
		}			

		if (empty($this->session->data['payment_methods'])) {
			$data['error_warning'] = sprintf($this->language->get('error_no_payment'), $this->url->link('information/contact'));
		} else {
			$data['error_warning'] = '';
		}	

		if (isset($this->session->data['payment_methods'])) {
			$data['payment_methods'] = $this->session->data['payment_methods']; 
		} else {
			$data['payment_methods'] = array();
		}
	  	
		if (isset($this->session->data['payment_method']['code'])) {
			$data['code'] = $this->session->data['payment_method']['code'];
		} else {
			$data['code'] = '';
		}
		
		if (isset($this->session->data['comment'])) {
			$data['comment'] = $this->session->data['comment'];
		} else {
			$data['comment'] = '';
		}
		
		if (isset($this->session->data['agree'])) { 
			$data['agree'] = $this->session->data['agree'];
		} else {
			$data['agree'] = '';
		}
			
		$json["payment_info"] = $data;

		//添加配送信息和获得积分信息
		$delivery_info = $this->getLogcentership();
		$json['delivery_info'] = $delivery_info['text'];
		$total = $this->cart->getSubTotal();
		$json['rewards'] = (int)((float)$total/1000);

		//添加是否允许免息账期相关信息
		$json['is_magfin'] = $this->customer->getIsMagfin();
		$json['log_name'] = $this->customer->getLogName(); 
		$json['log_user'] = $this->customer->getLogUser(); 
		$json['log_telephone'] = $this->customer->getLogTelephone();

        if ($this->debugIt) {
            echo '<pre>';
            print_r($json);
            echo '</pre>';
        } else {
            $this->response->setOutput(json_encode($json));
        }
    }

  public function	setSampleCheckoutFlag() {
  	if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			$requestjson = file_get_contents('php://input');
			$requestjson = json_decode($requestjson, true);
			$post		 = $requestjson;

			if(isset($post['sample_checkout']) && $post['sample_checkout']==1) {
				$this->load->model('account/customer');
				$customer_info = $this->model_account_customer->getCustomer($this->customer->getId());
				if(isset($customer_info['sample_bill_amount'])&&$customer_info['sample_bill_amount']!=0) {
					$json['success'] = false;
					$json["error"]['warning']		= '此用户已免费拿样过';
					$this->response->setOutput(json_encode($json));
					return;
				}
				//强制购物车商品数量全部为1
				$cart_qty_storage = array();
				$cur_products = $this->cart->getProducts();
				foreach ($cur_products as $product) {
					$cart_qty_storage[$product['cart_id']] = $product['quantity'];
				}
				$this->session->data['cart_qty_storage'] = $cart_qty_storage;
				// 
				foreach ($cart_qty_storage as $cart_id => $qty) {
					$this->cart->update($cart_id, 1);
				}
	  		//Check cart 满足 免费拿样条件
	  		$err_msg = $this->verifyCartForSample();
	  		if($err_msg != '') {
					$json['success'] = false;
					$json["error"]['warning']		= $err_msg;

					//购物车商品数量恢复
					$cart_qty_storage = $this->session->data['cart_qty_storage'];
					
					$cur_products = $this->cart->getProducts();
					foreach ($cur_products as $product) {
						if(array_key_exists($product['cart_id'], $cart_qty_storage)) {
							$qty_tmp = max($cart_qty_storage[$product['cart_id']], $product['minimum']);
						}
						$this->cart->update($product['cart_id'], $qty_tmp);
					}
					unset($this->session->data['sample_checkout']);
					
				} else {
					$this->session->data['sample_checkout'] = $post['sample_checkout'];
					$json['success'] = true;
					$json['message'] = '添加首次拿样标记成功';
				}
			} else {
				//购物车商品数量恢复
				$cart_qty_storage = $this->session->data['cart_qty_storage'];
				
				$cur_products = $this->cart->getProducts();
				foreach ($cur_products as $product) {
					if(array_key_exists($product['cart_id'], $cart_qty_storage)) {
						$qty_tmp = max($cart_qty_storage[$product['cart_id']], $product['minimum']);
					}
					$this->cart->update($product['cart_id'], $qty_tmp);
				}

				$json['success'] = true;
				$json['message'] = '清空首次拿样标记成功';
				unset($this->session->data['sample_checkout']);
			}
			$this->response->setOutput(json_encode($json));
		}
  }
  public function verifyCartForSample() {
  	// 验证订单总金额是否满足条件.
		$products = $this->cart->getProducts();
		$total = 0;
		$err_msg = '';
		foreach ($products as $product) {
			if($product['quantity']>1) {
				$err_msg .= $product['name'] . ' 最多只能免费拿一件; ';
			}
			$total += (float)$product['total'];
		}
		
		if($total < 500) {
			$err_msg = '免费拿样订单单件总金额需要大于500元。当前金额为' . $total . '元';
		}
		return $err_msg;
  }	

  public function verifyCartForSample_Old() {
  	// Validate minimum quantity requirements.
		$products = $this->cart->getProducts();

		$max_sample_qty = array();
		$product_ids = array();
		foreach ($products as $product) {
			$product_ids[] = $product['product_id'];
			//没有设置最大拿样属性的商品，配置拿样量为1
			$max_sample_qty[$product['product_id']] = array('max_sample_qty'=>1);
		}
		if(count($product_ids) == 0) {
			return true;
		}
		$product_ids = implode(',', $product_ids);
		$this->load->model('catalog/product');
		$sample_qtys = $this->model_catalog_product->getMaxSampleQty($product_ids);
		foreach ($sample_qtys as $sample_qty) {
			$max_sample_qty[$sample_qty['product_id']]['max_sample_qty'] = $sample_qty['sample_qty'];
		}
		
		$err_msg = '';
		foreach ($products as $product) {
			$product_total = 0;

			foreach ($products as $product_2) {
				if ($product_2['product_id'] == $product['product_id']) {
					$product_total += $product_2['quantity'];
				}
			}
			if($product_total > $max_sample_qty[$product['product_id']]['max_sample_qty']) {
				$err_msg .= $product['name'] . ' 超出最大拿样量 ' . $max_sample_qty[$product['product_id']]['max_sample_qty'] . '; ';
			}
		}

		return $err_msg;
  }

  public function getLogcentership(){
      $this->load->model('catalog/product');
      $logcenter_id = $this->customer->getLogcenterId();
      $data = array();
      $data['logcenter_zone_name'] =  $this->model_catalog_product->getLogcenterInfoByLogcenterId($logcenter_id);
      $data['time'] = '5';
      $data['text'] = !empty($data['logcenter_zone_name'])?'从'.$data['logcenter_zone_name'].' 物流中心 发货预计'.$data['time'].'天到达':'无';
      return $data;
  }

  public function fastpay(){
  	if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
		$requestjson = file_get_contents('php://input');	
		$requestjson = json_decode($requestjson, true);
		$post		 = $requestjson;
		$order_id = $post['order_id'];
		$payment_code = $post['payment_code'];
		$order_info = M('order')->where('order_id='.$order_id)->find();
		if($order_id&&$payment_code&&$order_info){

			$this->session->data['order_id'] = $order_id;
			if('kj_yijipay' == $payment_code || 'wx_yijipay' == $payment_code){
				$json['redirect'] = $this->load->controller('payment/' . $payment_code);
				$json['payment'] = $payment_code;
				$this->response->addHeader('Content-Type: application/json');
				$this->response->setOutput(json_encode($json));
			}else{
	        $data['payment'] = $this->load->controller('payment/' . $payment_code);
	        $this->gateway_pay($data);
	        }
	  	}
	}
}
	
	//余额支付
	public function payBalance($customer_id,$total){

		$this->checkPlugin();
		
		$json = array('success' => true);
		
		//用户扣除余额
		$this->load->model('balance/balance');
		$this->model_balance_balance->payBalance($customer_id,$total);

		$this->load->model('checkout/order');
		$comment = "";	
		if(isset($this->session->data['comment'])){
			$comment = $this->session->data['comment'];		
		}
		$data['is_pay'] = 1;
		$map['order_id'] = $this->session->data['order_id'];
		M('order')->where($map)->data($data)->save();
		$res = $this->model_balance_balance->getOrderById($map['order_id']);
		
		if ($res) {
			$this->model_balance_balance->updatemoney($res,$map['order_id']);
		}
		if(isset($this->session->data['order_id'])){

			$this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->model_checkout_order->findOrderStatus('待审核'), $comment);

			if (isset($this->session->data['order_id'])) {
                		$json['order_id'] = $this->session->data['order_id'];
				$this->cart->clear();

							// Add to activity log
			$this->load->model('account/activity');

			if ($this->customer->isLogged()) {
				$activity_data = array(
					'customer_id' => $this->customer->getId(),
					'name'        => $this->customer->getFullname(),
					'order_id'    => $this->session->data['order_id']
				);

				$this->model_account_activity->addActivity('order_account', $activity_data);
			} else {
				$activity_data = array(
					'name'     => $this->session->data['guest']['fullname'] ,
					'order_id' => $this->session->data['order_id']
				);

				$this->model_account_activity->addActivity('order_guest', $activity_data);
			}

			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);
			unset($this->session->data['guest']);

            if(isset($this->session->data['comment'])){
				unset($this->session->data['comment']);			
			}			
			unset($this->session->data['order_id']);
			unset($this->session->data['coupon']);
			unset($this->session->data['reward']);
			unset($this->session->data['voucher']);
			unset($this->session->data['vouchers']);
			unset($this->session->data['totals']);
			unset($this->session->data['sample_checkout']);

			}	
		}else {
			$json["success"] = false;
			$json["error"]['warning']= "没有订单";
		}
		if ($this->debugIt) {
				echo '<pre>';
				print_r($json);
				echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}
	
	}
	
	//检查用户是否首单
	public function checkFirst($customer_id){

		$this->load->model('checkout/customer');
		$check = $this->model_checkout_customer->checkFirst($customer_id);

		return $check;

	}

}
